package cn.minsh.lims.eoms.modules.app.controller;

import cn.minsh.lims.eoms.common.utils.PageUtils;
import cn.minsh.lims.eoms.common.utils.R;
import cn.minsh.lims.eoms.modules.app.controller.req.app.AppUserInspectionListReq;
import cn.minsh.lims.eoms.modules.app.controller.req.app.AppUserInspectionSubmitAndCloseReq;
import cn.minsh.lims.eoms.modules.app.controller.req.app.AppUserInspectionSubmitResultReq;
import cn.minsh.lims.eoms.modules.app.controller.res.UserInspectionPlanInfoRes;
import cn.minsh.lims.eoms.modules.app.controller.res.UserInspectionPlanRes;
import cn.minsh.lims.eoms.modules.app.entity.PlanAgentEntity;
import cn.minsh.lims.eoms.modules.app.entity.UserInspectionPlanEntity;
import cn.minsh.lims.eoms.modules.app.enums.BusiTypeEnum;
import cn.minsh.lims.eoms.modules.app.enums.PlanStatusEnum;
import cn.minsh.lims.eoms.modules.app.service.PlanAgentService;
import cn.minsh.lims.eoms.modules.app.service.UserInspectionPlanService;
import cn.minsh.lims.eoms.common.utils.ParamUtils;
import cn.minsh.lims.eoms.modules.app.utils.UserUtils;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;


/**
 * 用户巡检计划
 *
 * @author lht
 * @email sunlightcs@gmail.com
 * @date 2021-04-26 02:30:42
 */
@RestController
@RequestMapping("app/userInspectionPlan")
@Api(tags = "手机端-巡检工单(优化巡检)")
public class AppInspectionOrderController extends AbstractController{
    @Autowired
    private UserInspectionPlanService userInspectionPlanService;
    @Autowired
    private PlanAgentService planAgentService ;

    /**
     * 列表
     */
    @PostMapping("/list")
    @ApiOperation("巡检列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = UserInspectionPlanRes.class)
    })
    public R list(@RequestBody AppUserInspectionListReq req, HttpServletRequest request){
        PageUtils page = userInspectionPlanService.queryAppPage(req, UserUtils.getUserId(request));
        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation("巡检详情")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = UserInspectionPlanInfoRes.class)
    })
    public R info(@PathVariable("id") Long id,HttpServletRequest request){
        UserInspectionPlanInfoRes userInspectionPlan = userInspectionPlanService.queryById(id);
        userInspectionPlan.setLoginUserId(UserUtils.getUserId(request));
        return R.ok().put("data", userInspectionPlan);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserInspectionPlanEntity userInspectionPlan){
		userInspectionPlanService.save(userInspectionPlan);

        return R.ok();
    }

    /**
     * 开始巡检
     */
    @PutMapping("/start")
    @ApiOperation("巡检")
    public R start(@RequestParam("id")Long id,HttpServletRequest req){
        UserInspectionPlanEntity planEntity = userInspectionPlanService.getById(id) ;
        if (planEntity == null || planEntity.getId()==null){
            return R.error("记录不存在") ;
        }
        //判断是否开始了
        if (!new Date().equals(planEntity.getPlanStartTime()) && new Date().before(planEntity.getPlanStartTime())){
            return R.error("该巡检工单未开始") ;
        }
        /*if (planEntity.getStatus().equals(PlanStatusEnum.NOT_STARTED.getCode())){
            return R.error("该巡检工单未开始") ;
        }*/
        if (planEntity.getStatus().equals(PlanStatusEnum.OVER.getCode())){
            return R.error("巡检工单已结束") ;
        }
        List<PlanAgentEntity> planAgentEntityList = planAgentService.listByTypeAndPlanId(BusiTypeEnum.INSPECTIONORDER.getCode(),id) ;
        if (CollectionUtils.isEmpty(planAgentEntityList)){
            return R.error("该巡检工单没有经办人") ;
        }
        Long agentId = UserUtils.getUserId(req) ;
        Long count = planAgentEntityList.stream().filter(p->p.getAgentId().equals(agentId)).count() ;
        //登录人和经办人为同一个人
        if (count == null ||count==0){
            return R.error("当前登录人非经办人") ;
        }
        planEntity.setStatus(PlanStatusEnum.STARTED.getCode());
        planEntity.setCheckType(0);
        userInspectionPlanService.updateById(planEntity) ;

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/submitAndClose")
    @ApiOperation("提交并关闭工单")
    public R submitAndClose(@RequestBody @Valid AppUserInspectionSubmitAndCloseReq req, BindingResult bindingResult, HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            userInspectionPlanService.submitAndClose(req,UserUtils.getUserId(request));
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    /**
     * 提交巡检结果
     */
    @PutMapping("/submitResult")
    @ApiOperation("提交巡检结果（新接口）")
    public R submitResult(@RequestBody @Valid AppUserInspectionSubmitResultReq req, BindingResult bindingResult, HttpServletRequest request){
        try {
            ParamUtils.check(bindingResult);
            userInspectionPlanService.submitResult(req,UserUtils.getUserId(request));
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    /**
     * 关闭工单
     * @param id
     * @param request
     * @return
     */
    @PutMapping("/close")
    @ApiOperation("关闭工单(新接口)")
    public R close(@RequestParam("id")Long id, HttpServletRequest request){
        try {
            userInspectionPlanService.close(id,UserUtils.getUserId(request));
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage()) ;
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public R delete(@RequestParam("id") Long id){

        userInspectionPlanService.getById(id) ;

        return R.ok();
    }

}
